package com.itheima.rpc.client.proxy;

import com.itheima.rpc.client.request.RpcRequestManager;
import com.itheima.rpc.data.RpcRequest;
import com.itheima.rpc.data.RpcResponse;
import com.itheima.rpc.exception.RpcException;
import com.itheima.rpc.spring.SpringBeanFactory;
import com.itheima.rpc.util.RequestIdUtil;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @description 具体的生成代理的逻辑
 * @author: ts
 * @create:2021-05-12 00:11
 */
public class CglibProxyCallBackHandler implements MethodInterceptor {


    public Object intercept(Object o, Method method, Object[] parameters, MethodProxy methodProxy) throws Throwable {
        //不代理Object中的方法
        if(ReflectionUtils.isObjectMethod(method)){
            return method.invoke(method.getDeclaringClass().newInstance(),parameters);
        }
        //构造请求参数
        String id = RequestIdUtil.requestId();
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        RpcRequest rpcRequest = RpcRequest.builder()
                .requestId(id)
                .className(className)
                .methodName(methodName)
                .parameterTypes(parameterTypes)
                .parameters(parameters).build();
        //发送请求
        RpcRequestManager requestManager = SpringBeanFactory.getBean(RpcRequestManager.class);
        if (requestManager==null) {
            throw new RpcException("requestManager没有注入到IOC对象中");
        }
        RpcResponse rpcResponse=requestManager.sendRequest(rpcRequest);
        return rpcResponse.getResult();
    }
}
